package com.maotouying.tmtapp.fragment;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.maotouying.tmtapp.R;
import com.maotouying.tmtapp.activity.WebActivity;
import com.maotouying.tmtapp.adapter.NewsAdapter;
import com.maotouying.tmtapp.api.Api;
import com.maotouying.tmtapp.api.ApiConfig;
import com.maotouying.tmtapp.api.TitleCallback;
import com.maotouying.tmtapp.entity.NewsEntity;
import com.maotouying.tmtapp.entity.NewsListResponse;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 *
 * @description 
 * @author mingtai
 * @time 2020/11/22 23:41
 *
 */
public class NewsFragment extends BaseFragment {


    // 刷新使用的属性
    private RecyclerView recyclerView;
    private RefreshLayout refreshLayout;
    private int pageNum = 1;

    private NewsAdapter newsAdapter;
    private List<NewsEntity> datas = new ArrayList<>();

    // 全局布局管理器，兼容播放器的
    private LinearLayoutManager linearLayoutManager;

    // 在UI线程里面执行
    private Handler mHandler = new Handler() {
        @SuppressLint("HandlerLeak")
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    newsAdapter.setDatas(datas);
                    // 通知recycleView刷新页面
                    newsAdapter.notifyDataSetChanged();
                    break;
                default:
                    throw new IllegalStateException("Unexpected value: " + msg.what);
            }
        }
    };

    public NewsFragment() {

    }


    public static NewsFragment newInstance() {

        NewsFragment fragment = new NewsFragment();

        return fragment;
    }

    @Override
    protected int initLayout() {

        return R.layout.fragment_news;
    }

    @Override
    protected void initView() {

        //初始化布局 使用插件的刷新
        recyclerView = mRootView.findViewById(R.id.recycleView);
        refreshLayout = mRootView.findViewById(R.id.refreshLayout);
    }

    @Override
    protected void initDate() {

        //getActivity()获取父控件
        linearLayoutManager = new LinearLayoutManager(getActivity());
        //设置垂直排列
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(linearLayoutManager);

        newsAdapter = new NewsAdapter(getActivity());

        // for (int i = 0; i < 15; i++) {
        //     int type = i % 3 + 1;
        //     NewsEntity newsEntity = new NewsEntity();
        //     newsEntity.setType(type);
        //     datas.add(newsEntity);
        // }

        // 把数据放在newsAdapter适配器里面
        newsAdapter.setDatas(datas);
        //渲染到recycle view 绑定到recyclerView
        recyclerView.setAdapter(newsAdapter);

        newsAdapter.setOnItemClickListener(new NewsAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(Serializable obj) {
                showToast("点击跳转了...");
                NewsEntity newsEntity = (NewsEntity) obj;
                String url = "https://www.tmall.com/";
                Bundle bundle = new Bundle();
                bundle.putString("url", url);
                navigateToWithBundle(WebActivity.class, bundle);
            }
        });
        // 设置刷新
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                refreshlayout.finishRefresh(2000/*,false*/);//传入false表示刷新失败
                // 每次刷新，首页
                pageNum = 1;
                // 调用刷新的方法并且设置为true
                getNewsList(true);
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                // 加载，不需要刷新
                // refreshlayout.finishLoadMore(2000/*,false*/);//传入false表示加载失败
                // 每次加载 pageNum++
                pageNum++;
                getNewsList(false);
                // Log.d(TAG, "第页码数字" + pageNum);

            }
        });

        getNewsList(true);
    }

    // 获取资讯列表
    private void getNewsList(final boolean isRefresh) {
        // String token = getStringFromSp("token");
        // 把token放在请求头中，根据后端返回进行处理，不需要判断token是否为空了
        // if (!StringUtils.isEmpty(token)) {
        HashMap<String, Object> params = new HashMap<>();
        // params.put("token", token);
        params.put("limit", ApiConfig.PAGE_SIZE);
        Api.config(ApiConfig.NEWS_LIST, params).getRequest(getActivity(), new TitleCallback() {
            @Override
            public void onSuccess(String res) {
                if (isRefresh) {
                    refreshLayout.finishRefresh(true); //如果是刷新，关闭下拉刷新动画
                } else {
                    refreshLayout.finishLoadMore(true); // 关闭动画
                }

                final NewsListResponse response = new Gson().fromJson(res, NewsListResponse.class);
                if (response != null && response.getCode() == 0) {

                    List<NewsEntity> list = response.getPage().getList();
                    if (list != null && list.size() > 0) {
                        if (isRefresh) {
                            datas = list;
                        } else {
                            datas.addAll(list);
                        }
                        mHandler.sendEmptyMessage(0);

                    } else {
                        if (isRefresh) {
                            // 换成异步toast就可以不操作UI了
                            // showToast("加载无数据");
                            showToastSync("加载无数据");
                        } else {
                            showToastSync("没有更多数据了");
                        }
                    }


                }
            }

            @Override
            public void onFailure(Exception e) {
                // 接口请求失败，关闭动画
                if (isRefresh) {
                    refreshLayout.finishRefresh(true); //如果是刷新，关闭下拉刷新动画
                } else {
                    refreshLayout.finishLoadMore(true); // 关闭动画
                }
            }
        });

        // } else {
        //     navigateTo(LoginActivity.class);
        // }

    }
}